package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Handler;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author 龙龙龙
 * @since 2022-01-21
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource
    private IntegralGradeMapper integralGradeMapper;

    @Autowired
    private DictService dictService;

    @Autowired
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerService borrowerService;

    @Autowired
    private LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        BigDecimal bigDecimal = new BigDecimal("0");
        //先通过userId获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Integer integral = userInfo.getIntegral();

        //再通过积分获取用户额度
        QueryWrapper<IntegralGrade> userIntegralQueryWrapper = new QueryWrapper<>();
        userIntegralQueryWrapper.
                le("integral_start",integral)  //integral_start less equal than integral
                .gt("integral_end",integral); //integral_end greater equal than integral
            //考虑到0的情况 应该左闭右开

        IntegralGrade integralGradeConfig =integralGradeMapper.selectOne(userIntegralQueryWrapper);
        if(integralGradeConfig == null){
            return new BigDecimal("0");
        }
        return integralGradeConfig.getBorrowAmount();
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo ,Long userId) {

        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);

        //存储数据
        borrowInfo.setUserId(userId);
        //百分比转成小数
        borrowInfo.setBorrowYearRate( borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.eq("user_id",userId);
        BorrowInfo borrowInfo = baseMapper.selectOne(borrowInfoQueryWrapper);

        if(borrowInfo == null){
            //借款人尚未提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        return borrowInfo.getStatus();
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfos = baseMapper.selectList(null);


        for (BorrowInfo borrowInfo : borrowInfos) {
            Map<String ,Object> map = new HashMap<>();

            Integer returnMethod = borrowInfo.getReturnMethod();
            Integer moneyUse = borrowInfo.getMoneyUse();

            map.put("returnMethod",dictService.getNameByParentDictCodeAndValue("returnMethod", returnMethod));
            map.put("moneyUse",dictService.getNameByParentDictCodeAndValue("moneyUse", moneyUse));
            map.put("status",BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
            borrowInfo.setParam(map);
            Long userId = borrowInfo.getUserId();
            UserInfo userInfo = userInfoMapper.selectById(userId);
            borrowInfo.setName(userInfo.getName());
            borrowInfo.setMobile(userInfo.getMobile());
        }
        return borrowInfos;
    }

    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> resultMap = new HashMap<>();

        //查询借款人信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);

        //查询借款信息
        //组装数据
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);

        //根据user_id获取借款人对象
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.eq("user_id", borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(borrowerQueryWrapper);
        BorrowerDetailVO borrowerDetailVO= borrowerService.getBorrowerDetailVOById(borrower.getId());


        resultMap.put("borrower",borrowerDetailVO);
        resultMap.put("borrowInfo",borrowInfo);
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        //修改借款信息状态
        Long borrowInfoId = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过则创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            //创建标的
            BigDecimal lendYearRate = borrowInfoApprovalVO.getLendYearRate();
            BigDecimal serviceRate = borrowInfoApprovalVO.getServiceRate();
            lendYearRate= lendYearRate.divide(new BigDecimal(100));
            serviceRate = serviceRate.divide(new BigDecimal(100));
            borrowInfoApprovalVO.setLendYearRate(lendYearRate);
            borrowInfoApprovalVO.setServiceRate(serviceRate);
            //
            lendService.createLend(borrowInfoApprovalVO,borrowInfo);

        }
    }
}
